// 用户路由模块
const express = require("express");
// 创建并返回一个路由对象(使用express模块中的Router()方法)
// 引入mysql
// const mysql = require("mysql");
const db = require("../DB/dbconfig");
const upload = require("../DB/uploadconfig");
const userRouter = express.Router();
// 等价写法
// const { Router } = require("express");
// const userRouter = Router();
// 公开这个路由对象（公开目的 让require()来引用路由模块），如果不公开会返回一个空对象{}
module.exports = userRouter;
// 搜索、查询用get请求

// userRouter.route("/login").get(function (request, response) {
//   console.log(request.query); //get 请求的参数
//   // const{username,password}=request.query//es6中结构赋值的语法
//   // 通过name 名 取得
//   let username = request.query.username;
//   let password = request.query.password;
//   if (username === "qwe" && password === "123") {
//     response.redirect("/pages/main.html"); //登录成功，重定向到下一个页面
//   } else {
//     response.redirect("/index.html"); //登录失败，回到index
//   }
//   // 重定向（一定要以“/”开头）
//   //   response.redirect("/pages/main.html");
//   //   绝对路径
//   //   response.sendFile("");
// });
// // post请求：request.body来获取参数
// userRouter.route("/login").post((req, res) => {
//   console.log(`req.body`, req.body);
//   let password = req.body.password;
//   let username = req.body.username;
//   // 判断账号、密码
//   if (!username || !password) {
//     // 返回给前端
//     // res.json({
//     //   code: 4001,
//     //   msg: "账号、密码不能为空",
//     // });
//     res.redirect("/index.html");
//     return;
//   }
//   // 创建sql语句，不能直接拼接变量，只能用？来占位，避免sql注入的安全问题发生
//   // sql语句最后一定要加;
//   const sql = `select * from users where uaccess=? and upassword =?;`;
//   const params = [username, password]; // 数组元素必须与？的具体值匹配
//   const cb = (err, data) => {
//     //err,当执行sql发生错误时（语句语法错误），err的值就不是null
//     //data, 查询成功后的结果、[]的形式展示
//     console.log(`err`, err);//检测mysql语句错误
//     console.log(`data`, data);
//     // mysql中一行数据就是一个对象
//     // 响应前端请求
//     if (err === null && data.length === 1) {
//       res.redirect("/pages/main.html");
//     } else {
//       res.redirect("/index.html");
//     }
//   };
//   // if (username === "qwe" && password === "123") {
//   //   // index.html->/login -> /index.html 跳回
//   //   res.redirect("/pages/main.html"); //登录成功，重定向到下一个页面
//   // } else {
//   //   res.redirect("/index.html"); //登录失败，回到index
//   // }

// 基于ajax
// post请求：request.body来获取参数
userRouter.route("/login").post((req, res) => {
  // data 前端传过来的数据
  let password = req.body.password;
  let username = req.body.username;
  // console.log(`password,username`, password, username);
  // 判断账号、密码(如果前端判断了，后端就不会有问题)
  if (!/^\w{6,20}$/.test(username)) {
    // 返回给前端
    res.json({
      code: 4001,
      msg: "后端检测：账号不能为空或者长度不正确！",
    });
    return;
  }
  if (!/^\w{6,8}$/.test(password)) {
    // 返回给前端
    res.json({
      code: 4002,
      msg: "后端检测：密码不能为空或者长度不正确！",
    });
    return;
  }
  // 创建sql语句，不能直接拼接变量，只能用？来占位，避免sql注入的安全问题发生
  // sql语句最后一定要加;
  const sql = `select * from users where uaccess=? and upassword =?;`; // ?可以用${}代替
  const params = [username, password]; // 数组元素必须与？的具体值匹配
  const cb = (err, data) => {
    //err,当执行sql发生错误时（语句语法错误），err的值就不是null
    //data, 查询成功后的结果、[]的形式展示
    // console.log(`err`, err); //检测mysql语句错误
    // console.log(`data`, data);
    // mysql中一行数据就是一个对象
    // 响应前端请求
    if (err === null && data.length === 1) {
      res.json({
        code: 0,
        msg: "后端验证：登录成功",
        dataToFront: data,
      });
    } else {
      res.json({
        code: 4003,
        msg: "后端验证：登录失败",
        dataToFront: [],
      });
    }
  };
  // if (username === "qwe" && password === "123") {
  //   // index.html->/login -> /index.html 跳回
  //   res.redirect("/pages/main.html"); //登录成功，重定向到下一个页面
  // } else {
  //   res.redirect("/index.html"); //登录失败，回到index
  // }

  // // 操作数据库的步骤：
  // // 1. 创建一个链接对象
  // const conn = mysql.createConnection({
  //   host: "localhost", //目标数据库所在电脑的IP地址
  //   // host:"localhost",
  //   port: "3306",
  //   user: "root",
  //   password: "123qwe",
  //   database: "mydoctor", //数据库的名字
  //   multipleStatements: true, //支持执行多条sql语句
  //   timezone: "08:00", //设置时区，如果不匹配，就可能有时差
  // });
  // conn.connect(); //2. 打开连接
  // conn.query(sql, params, cb); //3. 执行mysql语句
  // conn.end(); //4. 关闭连接
  db.connect(sql, params, cb);
});
userRouter.route("/access/getAccess").get((req, res) => {
  let sql = "select * from permissions;";
  let params = [];
  let cb = (err, data) => {
    if (!err) {
      res.json({
        code: 0,
        msg: "查询成功",
        data,
      });
    } else {
      res.json({
        code: 4003,
        msg: "查询失败",
        data: [],
      });
    }
  };
  db.connect(sql, params, cb);
});

// #NOTE:搜索接口
userRouter.route("/access/find").get((req, res) => {
  // 必须在前端使用接口的时候传递搜索的内容
  let text = req.query.text; // -> undefined
  // const{text}=req.query
  console.log(`{text}`, { text });
  let sql = `select * from permissions where pname like ?;`;
  let params = [`%${text}%`];
  let cb = (err, data) => {
    if (!err) {
      res.json({
        code: 0,
        msg: "查询成功",
        data,
      });
    } else {
      res.json({
        code: 4003,
        msg: "查询失败",
        data,
      });
    }
  };
  db.connect(sql, params, cb);
});

userRouter.route("/access/delAccess").post((req, res) => {
  const { acid } = req.body;
  if (!acid) {
    res.json({
      code: 4005,
      msg: "缺少acid参数",
    });
    return;
  }
  console.log(`req.body`, req.body);
  let sql = `delete from permissions where pid=?;`;
  let params = [acid];
  let cb = (err, data) => {
    if (!err) {
      res.json({
        code: 0,
        msg: "删除权限成功",
      });
    } else {
      res.json({
        code: 4001,
        msg: "删除权限失败",
      });
    }
  };
  db.connect(sql, params, cb);
});

userRouter.route("/access/add").post((req, res) => {
  // console.log(`req.body`, req.body)
  let { pname, pdes } = req.body;
  let sql = `insert into permissions(pname,pdes) values(?,?);`;
  let params = [pname, pdes];
  let cb = (err, data) => {
    if (!err) {
      res.json({
        code: 0,
        msg: "添加权限成功",
      });
    } else {
      res.json({
        code: 4001,
        msg: "添加权限失败",
      });
    }
  };
  db.connect(sql, params, cb);
});
// #NOTE: 后端分页
userRouter.route("/user/getAll").get((req, res) => {
  let { pageNow, pageSize } = req.query;
  // 前后端都可以分页，
  // 做判断,有参数，后端分页，没有参数，前端分页
  if (!pageNow && !pageSize) {
    // 返回所有数据，让前端分页
    let sql = `select * from users;`;
    let cb = (err, data) => {
      if (!err) {
        res.json({
          code: 0,
          msg: "查询所有用户成功",
          data,
        });
      } else {
        res.json({
          code: 4002,
          msg: "查询所有用户失败",
          data,
        });
      }
    };
    db.connect(sql, [], cb);
  } else {
    // 后端分页
    let sql = "select * from users limit ?,?;";
    let startIndex;
    startIndex = (pageNow - 1) * pageSize;
    pageSize = Number(pageSize);
    sql += "select count(*) as count from users;";
    let params = [startIndex, pageSize];
    let cb = (err, data) => {
      if (err === null) {
        res.json({
          code: 0,
          msg: "查询成功",
          data: data[0],
          count: data[1][0].count,
        });
      } else {
        res.json({
          code: 4001,
          msg: "查询失败",
        });
      }
    };
    db.connect(sql, params, cb);
  }
});
// NOTE: 修改用户信息接口
userRouter
  .route("/user/modifyUserInfo")
  .post(upload.single("uphoto"), (req, res) => {
    console.log(`req.file`, req.file);
    // 修改不了的就不用获取，uaccess, ustate
    const { uname, upassword, usex, usid, utel, uid } = req.body;
    if (!uid) {
      res.json({
        code: 4003,
        msg: "uid是必须要传的",
      });
      return;
    }
    let uphoto = "";
    if (req.file !== undefined) {
      uphoto = req.file.filename;
    }
    let sql = `update users set uname=?,upassword=?,usex=?,utel=?,usid=?${
      uphoto !== "" ? ",uphoto=?" : ""
    } where uid=?;`;
    let params = [uname, upassword, usex, utel, usid];
    uphoto !== "" ? params.push(uphoto) : "";
    params.push(uid);
    let cb = (err, data) => {
      console.log(`err`, err);
      if (err !== null) {
        res.json({
          code: 4003,
          msg: "更新失败",
        });
      } else {
        res.json({
          code: 0,
          msg: "更新成功",
        });
      }
    };
    db.connect(sql, params, cb);
  });
// NOTE: 修改用户状态的接口
/**
 * @param {String} ustate, 用户状态,required
 * @param {Number} uid , 用户ID， required
 */
userRouter.route("/user/changeState").post((req, res) => {
  const { ustate, uid } = req.body;
  console.log(`req.body`, req.body);
  if (!ustate || !uid) {
    res.json({
      code: 4001,
      msg: "uid, ustate是必须的",
    });
    return;
  }
  let sql = `update users set ustate=? where uid=?;`;
  let params = [ustate, uid];
  let cb = (err, data) => {
    console.log(`err`, err);
    if (err === null) {
      res.json({
        code: 0,
        msg: "更新用户状态成功",
      });
    } else {
      res.json({
        code: 4003,
        msg: "更新用户状态失败",
      });
    }
  };
  db.connect(sql, params, cb);
});
// NOTE: 用户删除接口
userRouter.route("/user/delete").post((req, res) => {
  let uid = req.body.uid;
  // console.log(`uid`, uid,typeof uid)
  let sql = `delete from users where uid =?;`;
  let params = [Number(uid)];
  let cb = (err, data) => {
    console.log(`err`, err);
    if (err === null) {
      res.json({
        code: 0,
        msg: "删除用户成功",
      });
    } else {
      res.json({
        code: 4001,
        msg: "删除用户失败",
      });
    }
  };
  db.connect(sql, params, cb);
});
// NOTE: 新增用户
userRouter.route("/user/add").post(upload.single("uphoto"), (req, res) => {
  const { uid, uname, upassword, usex, usid, utel } = req.body;
});
// NOTE: 获取所有角色数据
userRouter.route("/roles/getAll").get((req, res) => {
  let sql = "select * from roles";
  let params = [];
  let cb = (err, data) => {
    if (err === null) {
      res.json({ code: 0, msg: "查询成功", data });
    } else {
      res.json({ code: 4001, msg: "查询失败", data: [] });
    }
  };
  db.connect(sql, params, cb);
});
// NOTE:  获取一个用户已有的角色数据
userRouter.route("/user/getRoles").post((req, res) => {
  let { uid } = req.body;
  let sql = `select * from userroletable where uid=?;`;
  let params = [uid];
  let cb = (err, data) => {
    if (err === null) {
      res.json({ code: 0, msg: "获取角色成功", data });
    } else {
      res.json({ code: 4001, msg: "获取角色失败", data: [] });
    }
  };
  db.connect(sql, params, cb);
});
// 修改分配给用户的角色数据：
/**
 * @api: "/user/addRoles"
 * @method 'post'
 * @params uid, {Number},required
 * @params ridList, {Array},required,不能为空数组 [1,3,6,9]
 */
userRouter.route("/user/addRoles").post((req, res) => {
  let { uid, ridList } = req.body;
  let delApi = new Promise((resolve, reject) => {
    let sql = `delete from userroletable where uid=?`;
    let params = [uid];
    let cb = (err, data) => {
      // console.log(`+++++++++++++++err`, err);
      if (err === null) {
        resolve("1");
      } else {
        reject("删除失败");
      }
    };
    db.connect(sql, params, cb);
  })
    .then((value) => {
      if (ridList === undefined) {
        return "删除成功";
      } else {
        return new Promise((resolve, reject) => {
          let sql = `insert into userroletable (uid, rid) value `;
          let tempSql = [];
          let params = [];
          ridList.forEach((el) => {
            tempSql.push("(?,?)");
            params.push(uid, Number(el));
          });
          sql += tempSql;
          sql += ";";
          let cb = (err, data) => {
            if (err === null) {
              resolve("重新添加数据成功");
            } else {
              reject("重新添加数据失败");
            }
          };
          db.connect(sql, params, cb);
        });
      }
    })
    .then((value) => {
      res.json({ code: 0, msg: value });
    })
    .catch((value) => {
      res.json({
        code: 4001,
        msg: value,
      });
    });
});
